<template>
	<div class="topic-list">
		<el-form :inline="true" :model="dataForm" @keyup.enter.native="getListData()">
			<el-form-item>
				<el-input v-model="dataForm.title" placeholder="题目名称" clearable></el-input>
			</el-form-item>
			<el-form-item>
				<el-input v-model="dataForm.chapterName" placeholder="所属章节" clearable></el-input>
			</el-form-item>
			<el-form-item>
				<el-button @click="getListData()">查询</el-button>
				<el-button v-if="isAuth('topic:type:save')" type="primary" @click="saveHandle()">新增</el-button>
				<!-- <el-button v-if="isAuth('chapter:delete')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button> -->
				<!-- <el-button @click="requestImport()">导入</el-button> -->
				<el-button @click="requestExport()">导出</el-button>
			</el-form-item>
			<el-upload drag :limit=limitNum :auto-upload="false" accept=".xlsx" :action="UploadUrl()"
				:before-upload="beforeUploadFile" :on-change="fileChange" :on-exceed="exceedFile"
				:on-success="handleSuccess" :on-error="handleError" :file-list="fileList">
				<i class="el-icon-upload"></i>
				<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
				<div class="el-upload__tip" slot="tip">只能上传xlsx文件，且不超过10M</div>
			</el-upload>
			<el-button type="primary" @click="uploadFile">立即上传</el-button>
		</el-form>
		<el-table :data="dataList" style="width: 100%">
			<el-table-column type="expand">
				<template slot-scope="props">
					<el-form label-position="left" inline class="demo-table-expand">
						<el-form-item label="A">
							<span>{{ props.row.a }}</span>
						</el-form-item>
						<el-form-item label="B">
							<span>{{ props.row.b }}</span>
						</el-form-item>
						<el-form-item label="C">
							<span>{{ props.row.c }}</span>
						</el-form-item>
						<el-form-item label="D">
							<span>{{ props.row.d }}</span>
						</el-form-item>
						<el-form-item label="答案">
							<span>{{ props.row.trueAnswer }}</span>
						</el-form-item>
						<el-form-item label="解析">
							<span>{{ props.row.analysis }}</span>
						</el-form-item>
					</el-form>
				</template>
			</el-table-column>
			<el-table-column label="题目ID" prop="id" header-align="center" align="center">
			</el-table-column>
			<el-table-column label="题目名称" prop="title" header-align="center" align="center">
			</el-table-column>
			<el-table-column label="所属章节" prop="chapterName" header-align="center" align="center">
			</el-table-column>
			<el-table-column label="题库类型" prop="typeName" header-align="center" align="center">
			</el-table-column>
			<el-table-column label="标签" prop="label" header-align="center" align="center">
			</el-table-column>
			<el-table-column label="分值" prop="score" header-align="center" align="center">
			</el-table-column>
			<el-table-column label="创建时间" prop="createTime" header-align="center" align="center">
			</el-table-column>
			<el-table-column label="创建人" prop="createName" header-align="center" align="center">
			</el-table-column>
			<el-table-column label="更新时间" prop="updateTime" header-align="center" align="center">
			</el-table-column>
			<el-table-column label="更新人" prop="updateName" header-align="center" align="center">
			</el-table-column>
			<el-table-column prop="status" label="状态" header-align="center" align="center">
				<template slot-scope="scope">
					<el-tag v-if="scope.row.status === 0" size="small" type="warning">开发中</el-tag>
					<el-tag v-if="scope.row.status === 1" size="small">正常</el-tag>
					<el-tag v-if="scope.row.status === 2" size="small" type="danger">停用</el-tag>
				</template>
			</el-table-column>
			<el-table-column fixed="right" label="操作" header-align="center" align="center">
				<template slot-scope="scope">
					<el-button v-if="isAuth('topic:type:save')" @click="saveHandle(scope.row.id)" type="text"
						size="small">编辑</el-button>
					<el-button v-if="isAuth('topic:type:status:modify')" @click="deleteHandle(scope.row.id)" type="text"
						size="small">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!-- 弹窗, 新增 / 修改 -->
		<add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getListData"></add-or-update>

	</div>
</template>

<style>
	.demo-table-expand {
		font-size: 0;
	}

	.demo-table-expand label {
		width: 90px;
		color: #99a9bf;
	}

	.demo-table-expand .el-form-item {
		margin-right: 0;
		margin-bottom: 0;
		width: 50%;
	}
</style>

<script>
	import AddOrUpdate from './topic-add-or-update'
	export default {
		data() {
			return {
				dataForm: {
					title: '',
					chapterName: '',
				},
				dataList: [],
				pageIndex: 1,
				pageSize: 10,
				totalPage: 0,
				dataListLoading: false,
				dataListSelections: [],
				addOrUpdateVisible: false,
				limitNum: 1,  
				fileList: [],
			}
		},
		components: {
			AddOrUpdate
		},
		activated() {
			this.getListData()
		},
		methods: {
			getListData() {
				let _that = this
				this.dataListLoading = true
				this.$http({
					url: this.$http.adornUrl('/topic/list'),
					method: 'get',
					params: this.$http.adornParams({
						'page': this.pageIndex,
						'limit': this.pageSize,
						'title': this.dataForm.title,
						'chapterName': this.dataForm.chapterName
					})
				}).then(({
					data
				}) => {
					_that.dataList = []
					if (data && data.code === 0) {
						_that.dataList = data.data
						_that.totalPage = data.count
					} else {
						_that.dataList = []
						_that.totalPage = 0
					}
					this.dataListLoading = false
				})
			},
			requestExport() {
				this.$http({
					url: this.$http.adornUrl('/topic/export'),
					method: 'get',
					params: this.$http.adornParams({
						'page': 1,
						'title': this.dataForm.title,
						'chapterName': this.dataForm.chapterName
					}),
					responseType: 'blob'
				}).then((res) => {
					console.log(res)
					const link = document.createElement('a')
					let blob = new Blob([res.data], {
						type: 'application/vnd.ms-excel'
					});
					link.style.display = 'none'
					link.href = URL.createObjectURL(blob);
					let num = ''
					for (let i = 0; i < 10; i++) {
						num += Math.ceil(Math.random() * 10)
					}
					link.setAttribute('download', '试题' + num + '.xlsx')
					document.body.appendChild(link)
					link.click()
					document.body.removeChild(link)
				})
			},
			// 文件超出个数限制时的钩子
			exceedFile(files, fileList) {
				this.$message.warning(`只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length + fileList.length} 个`);
			},
			// 文件状态改变时的钩子
			fileChange(file, fileList) {
				console.log(file.raw);
				this.fileList.push(file.raw) ;
				console.log(this.fileList);
			},
			// 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
			beforeUploadFile(file) {
				console.log('before upload');
				console.log(file);
				let extension = file.name.substring(file.name.lastIndexOf('.') + 1);
				let size = file.size / 1024 / 1024;
				if (extension !== 'xlsx') {
					this.$message.warning('只能上传后缀是.xlsx的文件');
				}
				if (size > 10) {
					this.$message.warning('文件大小不得超过10M');
				}
			},
			// 文件上传成功时的钩子
			handleSuccess(res, file, fileList) {
				this.$message.success('文件上传成功');
			},
			// 文件上传失败时的钩子
			handleError(err, file, fileList) {
				this.$message.error('文件上传失败');
			},
			UploadUrl: function() {
				// 因为action参数是必填项，我们使用二次确认进行文件上传时，直接填上传文件的url会因为没有参数导致api报404，所以这里将action设置为一个返回为空的方法就行，避免抛错
				return ""
			},
			uploadFile() {
				if (this.fileList.length === 0) {
					this.$message.warning('请上传文件');
				} else {
					let form = new FormData();
					form.append('file', this.fileList[0]);
					this.$http({
						method: "post",
						url: this.$http.adornUrl('/topic/import'),
						headers: {
							'Content-type': 'multipart/form-data'
						},
						data: form
					}).then(
						res => {
			
						}, err => {});
				}
			
			},
			// 每页数
			sizeChangeHandle(val) {
				this.pageSize = val
				this.pageIndex = 1
				this.getListData()
			},
			// 当前页
			currentChangeHandle(val) {
				this.pageIndex = val
				this.getListData()
			},
			// 多选
			selectionChangeHandle(val) {
				this.dataListSelections = val
			},
			// 新增 / 修改
			saveHandle(id) {
				this.addOrUpdateVisible = true
				this.$nextTick(() => {
					this.$refs.addOrUpdate.init(id)
				})
			},
			// 删除
			deleteHandle(id) {
				var userIds = id ? [id] : this.dataListSelections.map(item => {
					return item.userId
				})
				this.$confirm(`确定对[id=${userIds.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$http({
						url: this.$http.adornUrl('/topic/delete'),
						method: 'post',
						data: this.$http.adornData(userIds, false),

					}).then(({
						data
					}) => {
						if (data && data.code === 0) {
							this.$message({
								message: '操作成功',
								type: 'success',
								duration: 1500,
								onClose: () => {
									this.getDataList()
								}
							})
						} else {
							this.$message.error(data.msg)
						}
					})
				}).catch(() => {})
			}
		}
	}
</script>
